﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace MvcImproved.Generic.Controls
{
	public class Hidden<TDataItem, TMemberValue> : GenericInputControl<TDataItem, TMemberValue>
	{
		public Hidden(Func<TDataItem, TMemberValue> valueMember)
			: base(valueMember, "hidden")
		{
		}

		protected override void ControlSpecificRender(HtmlTextWriter writer, SortedDictionary<string, string> attrs)
		{
			if (!DesignMode)
			{
				string attemptedValue = (string)GetModelStateValue(Name, typeof(string));

				if (attemptedValue != null)
				{
					// Never format the attempted value since it was already formatted in the previous request
					attrs.Add("value", attemptedValue);
				}
				else
				{
					// The HtmlTextWriter will automatically encode this value
					TMemberValue value = ValueMemberLambda(DataValue);
					if (value != null)
						attrs.Add("value", value.ToString());
					else
						attrs.Add("value", "");
				}
			}
		}
	}


	// Non-generic version of the control that's used in the actual markup
	[ControlBuilder(typeof(GenericControlBuilder))]
	[GenericControlType(typeof(Hidden<,>), MemberValue = "ValueMember", GenericParameters = "ModelType")]
	public class Hidden : Hidden<object, object>
	{
		public Hidden()
			: base(null)
		{ }

		public string ModelType
		{
			get;
			set;
		}
	}
}
